package vip.manda.framework.auth;

import cn.hutool.extra.servlet.ServletUtil;
import vip.manda.framework.core.Configs;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hongda.li 2022-04-02 20:46
 */
public class HttpManager {

    private static final String ACCESS_TOKEN = "access_token";

    public static String getToken(String tokenName, HttpServletRequest request){
        Cookie cookie = ServletUtil.getCookie(request, tokenName);
        return cookie != null ? cookie.getValue() : "";
    }

    public static String getAccessToken(HttpServletRequest request){
        return getToken(ACCESS_TOKEN, request);
    }

    public static void setAccessToken(String token, HttpServletResponse response){
        setToken(ACCESS_TOKEN, token, response);
    }

    public static void setToken(String tokenName, String token, HttpServletResponse response) {
        Cookie cookie = new Cookie(tokenName, token);
        cookie.setPath("/");
        cookie.setMaxAge(Configs.getInt(Configs.Auth.COOKIE_TIME));
        response.addCookie(cookie);
    }

    public static void clearAccessToken(HttpServletResponse response){
        clearToken(ACCESS_TOKEN, response);
    }

    public static void clearToken(String tokenName, HttpServletResponse response){
        Cookie cookie = new Cookie(tokenName, null);
        response.addCookie(cookie);
    }
}
